<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta name="baidu-site-verification" content="UqlC4pwKIm">
  <meta name="baidu-site-verification" content="d3U0dGeqGw">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="9Ho8iwjF7bDNkvQpVQHlhFPHnsfuMWlsOvTTgEPIuy4">














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  







<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="https://cdn.jsdelivr.net/gh/lopyfrontend/common@0.0.1/icon/favicon-180x180.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="https://cdn.jsdelivr.net/gh/lopyfrontend/common@0.0.1/icon/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="https://cdn.jsdelivr.net/gh/lopyfrontend/common@0.0.1/icon/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="linux,iptables,">





  <link rel="alternate" href="/atom.xml" title="码奴假娃" type="application/atom+xml">






<meta name="description" content="从前blog移植过来，暂无摘要，后期再补">
<meta name="keywords" content="linux,iptables">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux中iptables设置详细">
<meta property="og:url" content="https://blog.lopygo.com/2015/2015-2015-03-29-linux-iptables-setup/index.html">
<meta property="og:site_name" content="码奴假娃">
<meta property="og:description" content="从前blog移植过来，暂无摘要，后期再补">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2025-09-16T17:33:20.673Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Linux中iptables设置详细">
<meta name="twitter:description" content="从前blog移植过来，暂无摘要，后期再补">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://blog.lopygo.com/2015/2015-2015-03-29-linux-iptables-setup/">





  <title>Linux中iptables设置详细 | 码奴假娃</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-136884610-2', 'auto');
  ga('send', 'pageview');
</script>


  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?52567a573db99b54cccb66af4c41822b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">码奴假娃</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">裸皮狗</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://blog.lopygo.com/2015/2015-2015-03-29-linux-iptables-setup/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony Java Z">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="码奴假娃">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Linux中iptables设置详细</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2015-03-28T16:00:01+00:00">
                2015-03-29
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2025-09-16T17:33:20+00:00">
                2025-09-17
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/develop/" itemprop="url" rel="index">
                    <span itemprop="name">develop</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2015/2015-2015-03-29-linux-iptables-setup/" class="leancloud_visitors" data-flag-title="Linux中iptables设置详细">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,013
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <script src="/assets/js/APlayer.min.js"> </script><p>从前blog移植过来，暂无摘要，后期再补</p>
<a id="more"></a>
<p>无论如何，iptables是一个需要特别谨慎设置的东西，万一服务器不在你身边，而你贸然设置导致无法SSH，那就等着被老板骂吧，呵呵。。。</p>
<p>一下内容是为了防止这种情况发生而写的，当然很初级，不过一般服务器也够用了：</p>
<p>1.首先介绍一下指令和相关配置文件</p>
<ul>
<li>启动指令:service iptables start</li>
<li>重启指令:service iptables restart</li>
<li>关闭指令:service iptables stop</li>
</ul>
<p>然后是相关配置:/etc/sysconfig/iptables</p>
<ul>
<li>如何操作该配置呢？</li>
<li>vim /etc/sysconfig/iptables</li>
<li>然后进去修改即可，修改完了怎么办？这里很多人会想到/etc/rc.d/init.d/iptables save指令，但是一旦你这么干了你刚才的修改内容就白做了。。。</li>
</ul>
<p>具体方法是：</p>
<p>只修改/etc/sysconfig/iptables 使其生效的办法是修改好后先service iptables restart，然后才调用/etc/rc.d/init.d/iptables save，因为/etc/rc.d/init.d/iptables save会在iptables服务启动时重新加载，要是在重启之前直接先调用了/etc/rc.d/init.d/iptables save那么你的/etc/sysconfig/iptables 配置就回滚到上次启动服务的配置了，这点必须注意！！！</p>
<p>2.下面介绍一些指令用法（主要还是man iptables看下相关资料才行）</p>
<ul>
<li>-A：指定链名</li>
<li>-p：指定协议类型</li>
<li>-d：指定目标地址</li>
<li>–dport：指定目标端口（destination port 目的端口）</li>
<li>–sport：指定源端口（source port 源端口）</li>
<li>-j：指定动作类型</li>
</ul>
<p>3.如果我不像修改文件直接打命令可以吗，当然没问题，步骤如下:</p>
<p>例如我给SSH加放行的语句：</p>
<ul>
<li>添加input记录： iptables -A INPUT -p tcp –dport 22 -j ACCEPT</li>
<li>添加output记录： iptables -A OUTPUT -p tcp –sport 22 -j ACCEPT</li>
<li>最后注意需要再执行一下 /etc/init.d/iptables save，这样这两条语句就保存到刚才那个/etc/sysconfig/iptables 文件中了。</li>
</ul>
<p>4.接下来说明一下步骤，如果机器不在我身边，我只能SSH进去做iptables规则，那么我必须注意每一步，千万别搞错了，否则就SSH链接不上都有可能！</p>
<p>首先要做的是给咱的SSH进行ACCEPT配置，以免直接无法连接的情况发生:</p>
<p>1.如果SSH端口是22（这里不建议用默认端口最好改掉SSH端口）</p>
<ul>
<li>iptables -A INPUT -p tcp –dport 22 -j ACCEPT</li>
<li>iptables -A OUTPUT -p tcp –sport 22 -j ACCEPT</li>
<li>注意要/etc/rc.d/init.d/iptables save，以下每一步都最好执行一遍此语句，以下不再累述。</li>
</ul>
<p>2.vim /etc/sysconfig/iptables确定是否已经加入配置，可以的话执行service iptables restart重启后生效</p>
<p>3.下面是很危险的操作，如果你第一步没做就会直接可能导致你连不上SSH，此步骤前切记执行第一步！！！</p>
<ul>
<li>iptables -P INPUT DROP</li>
<li>iptables -P OUTPUT DROP</li>
<li>iptables -P FORWARD DROP</li>
</ul>
<p>这个步骤是把所有不符合自己配置的规则ACCEPT的连接全部DROP掉，执行完以后如果咱SSH还没掉，那么谢天谢地，安全了，重启下iptables后继续下面的配置！</p>
<p>4.下面咱就不细说了，具体就是看自己服务器要开放哪些端口或者是要访问哪些端口来做具体的配置，下面是我自己的机器的配置：</p>
<ul>
<li>/etc/sysconfig/iptables文件配置如下:</li>
<li>#Generated by iptables-save v1.4.7 on Fri Mar  2 19:59:43 2012</li>
<li>*filter</li>
<li>:INPUT DROP [0:0]</li>
<li>:FORWARD DROP [0:0]</li>
<li>:OUTPUT DROP [8:496]</li>
<li>-A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT</li>
<li>#ping使用的端口</li>
<li>-A INPUT -p icmp -j ACCEPT</li>
<li>-A INPUT -i lo -j ACCEPT</li>
<li>-A INPUT -s 127.0.0.1/32 -d 127.0.0.1/32 -j ACCEPT</li>
<li>-A INPUT -s 192.168.2.200/32 -d 192.168.2.200/32 -j ACCEPT</li>
<li>#允许服务器自己的SSH（对外部请求来说服务器是目标所以使用–dport）</li>
<li>-A INPUT -p tcp -m tcp –dport 22 -j ACCEPT</li>
<li>#80端口不用说了吧，服务器网站访问端口</li>
<li>-A INPUT -p tcp -m tcp –dport 80 -j ACCEPT</li>
<li>-A INPUT -p tcp -m tcp –dport 3306 -j ACCEPT</li>
<li>-A INPUT -p tcp -m tcp –dport 11211 -j ACCEPT</li>
<li>-A INPUT -p tcp -m tcp –dport 11212 -j ACCEPT</li>
<li>-A FORWARD -j REJECT –reject-with icmp-host-prohibited</li>
<li>#53端口是DNS相关，TCP和UDP都要配置</li>
<li>-A INPUT -p tcp -m tcp –dport 53 -j ACCEPT</li>
<li>-A INPUT -p udp -m udp –dport 53 -j ACCEPT</li>
<li>#ping使用的端口</li>
<li>-A OUTPUT -p icmp -j ACCEPT</li>
<li>-A OUTPUT -s 127.0.0.1/32 -d 127.0.0.1/32 -j ACCEPT</li>
<li>-A OUTPUT -s 192.168.2.200/32 -d 192.168.2.200/32 -j ACCEPT</li>
<li>#允许服务器SSH到其他机器（使用外部端口就使用–dport）</li>
<li>-A OUTPUT -p tcp -m tcp –dport 22 -j ACCEPT</li>
<li>#允许服务器自己的SSH（自已为源输出就使用–sport）</li>
<li>-A OUTPUT -p tcp -m tcp –sport 22 -j ACCEPT</li>
<li>#访问外部网站80端口（使用外部端口就使用–dport）</li>
<li>-A OUTPUT -p tcp -m tcp –dport 80 -j ACCEPT</li>
<li>#如果服务器需要访问外部网站，那么OUTPUT也需要配置53端口（使用外部端口就使用–dport）</li>
<li>-A OUTPUT -p tcp -m tcp –dport 53 -j ACCEPT</li>
<li>-A OUTPUT -p udp -m udp –dport 53 -j ACCEPT</li>
<li>#如果有访问外部邮箱，那么打开邮箱相关端口（使用外部端口就使用–dport）</li>
<li>-A OUTPUT -p tcp -m tcp –dport 465 -j ACCEPT</li>
<li>-A OUTPUT -p tcp -m tcp –dport 25 -j ACCEPT</li>
<li>-A OUTPUT -p tcp -m tcp –dport 110 -j ACCEPT</li>
<li>#服务器网站访问端口（自已为源输出就使用–sport）</li>
<li>-A OUTPUT -p tcp -m tcp –sport 80 -j ACCEPT</li>
<li>-A OUTPUT -p tcp -m tcp –sport 3306 -j ACCEPT</li>
<li>-A OUTPUT -p tcp -m tcp –sport 11211 -j ACCEPT</li>
<li>-A OUTPUT -p tcp -m tcp –sport 11212 -j ACCEPT</li>
<li>COMMIT</li>
<li>Completed on Fri Mar  2 19:59:43 2012</li>
</ul>
<p>5.可能有时候需要删除规则，最简单就是修改一下/etc/sysconfig/iptables然后service iptables restart,最后/etc/rc.d/init.d/iptables save即可。</p>
<p>当然也可以使用指令完成:</p>
<p>在网上找了一下，删除规则的方法：</p>
<p>语法是： iptables -D chain rulenum [options]</p>
<p>其中： chain 是链的意思，就是INPUT FORWARD 之类的<br>             rulenum 是规则的编号。从1 开始。可以使用  –line-numbers 列出规则的编号</p>
<p>所以，例如上面要删除一个INPUT链的规则的话可以这样：<br>    iptables -D INPUT 3</p>
<p>意思是删除第3条规则。</p>
<p>还有第二种方法。第二种办法是 -A 命令的映射，不过用-D替换-A。当你的链中规则很复杂，而你不想计算它们的编号的时候这就十分有用了。也就是说，你如何用iptables -A…. 语句定义了一个规则，则删除此规则时就用 -D 来代替- A  其余的都不变即可。</p>
<p>======================</p>
<p>说一下上面的 –line-numbers 选项，如下面的命令：</p>
<pre><code>iptables -L INPUT --line-numbers
</code></pre><p>列出INPUT 链所有的规则</p>
<ul>
<li>num  target     prot opt source               destination</li>
<li>1    REJECT     tcp  –  anywhere             anywhere            tcp dpt:microsoft-ds reject-with icmp-port-unreachable</li>
<li>2    REJECT     tcp  –  anywhere             anywhere            tcp dpt:135 reject-with icmp-port-unreachable</li>
<li>3    REJECT     tcp  –  anywhere             anywhere            tcp dpt:netbios-ssn reject-with icmp-port-unreachable</li>
</ul>
<p>…</p>
<p>…</p>
<p>删除指定行规则：</p>
<pre><code>[root@localhost rc.d]# iptables -D INPUT 4
</code></pre><p>  6.最后补充一下，如果想针对某IP进行单独开放端口可以如下配置：</p>
<p>如果我需要对内网某机器单独开放mysql端口，应该如下配置：</p>
<pre><code>iptables -A INPUT -s 192.168.2.6 -p tcp -m tcp --dport 3306 -j ACCEPT
iptables -A OUTPUT -s 192.168.2.6 -p tcp -m tcp --sport 3306 -j ACCEPT
</code></pre><p>7.彻底禁止某IP访问:</p>
<p>#屏蔽单个IP的命令是</p>
<pre><code>iptables -I INPUT -s 123.45.6.7 -j DROP
</code></pre><p>#封整个段即从123.0.0.1到123.255.255.254的命令</p>
<pre><code>iptables -I INPUT -s 123.0.0.0/8 -j DROP
</code></pre><p>#封IP段即从123.45.0.1到123.45.255.254的命令</p>
<pre><code>iptables -I INPUT -s 124.45.0.0/16 -j DROP
</code></pre><p>#封IP段即从123.45.6.1到123.45.6.254的命令是</p>
<pre><code>iptables -I INPUT -s 123.45.6.0/24 -j DROP
</code></pre><p>指令I是insert指令 但是该指令会insert在正确位置并不像A指令看你自己的排序位置，因此用屏蔽因为必须在一开始就要加载屏蔽IP，所以必须使用I命令加载，然后注意执行/etc/rc.d/init.d/iptables save进行保存后重启服务即可</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Tony Java Z
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://blog.lopygo.com/2015/2015-2015-03-29-linux-iptables-setup/" title="Linux中iptables设置详细">https://blog.lopygo.com/2015/2015-2015-03-29-linux-iptables-setup/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/linux/" rel="tag"># linux</a>
          
            <a href="/tags/iptables/" rel="tag"># iptables</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2015/2015-2015-03-20-mysql-updateupdate/" rel="next" title="MySql更新多条数据不建议使用UPDATE语句">
                <i class="fa fa-chevron-left"></i> MySql更新多条数据不建议使用UPDATE语句
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2015/2015-2015-05-19-debian-apt-source/" rel="prev" title="我的debian常用apt源">
                我的debian常用apt源 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="Tony Java Z">
            
              <p class="site-author-name" itemprop="name">Tony Java Z</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

			<!--my custom code begin-->
			<script src="https://cdn.jsdelivr.net/npm/jquery@3.1.0/dist/jquery.min.js"></script>
			<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.min.js"></script>
			<script type="text/javascript">
			  $("#sidebar").hover(function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 1});
			  },function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 0});
			  });
			</script>
			<div id="mydivshow" class="mydivshow">
			<!--my custom code end-->
			
          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">118</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">104</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/uljjmhn520" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:284141050 @qq.com" target="_blank" title="Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=pZedkZSRlJWQleXU1IvGysg" target="_blank" title="QQ邮我">
                    
                      <i class="fa fa-fw fa-envelope"></i>QQ邮我</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.lopygo.com" title="主站" target="_blank">主站</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.csdn.net/u011475210" title="WordZzzCsdn" target="_blank">WordZzzCsdn</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://wordzzzz.github.io" title="WordZzzGitPage" target="_blank">WordZzzGitPage</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.choudalao.com" title="臭大佬" target="_blank">臭大佬</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.wingflare.com" title="翼闪的奶嘴" target="_blank">翼闪的奶嘴</a>
                  </li>
                
              </ul>
            </div>
          

          
        </div>
		<!--my custom code begin-->
		</div>
		<!--my custom code end-->
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony Java Z</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">72.9k</span>
  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>




        
<div class="busuanzi-count">
  
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script src="https://cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fastclick@1.0.6/lib/fastclick.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-lazyload@1.9.7/jquery.lazyload.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.2.2/velocity.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@1.2.2/velocity.ui.min.js"></script>




  
  <script src="https://cdn.jsdelivr.net/npm/jquery-fancybox@2.0.0/source/js/jquery.fancybox.pack.js"></script>



  
  <script src="https://cdn.jsdelivr.net/npm/canvas-nest.js@1.0.0/canvas-nest.min.js"></script>












  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>




  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>



  
  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>


<script>
  console.log('%c本Blog仅用于个人学习',"color:orange; background:blue; font-size: 16pt");

  console.log('%c内容中有部分资源引用自互联网',"color:orange; background:blue; font-size: 16pt");

  console.log('%c如果不小心侵犯了您的权益，请联系  284141050@qq.com 处理相关信息',"color:orange; background:blue; font-size: 16pt");

</script>

</body>
</html>
